#!/bin/bash

set_bios_pciecardbdf() {
    source /etc/profile
    input=$(/data/script/load_pcie 0 | xargs)
    result=$(/opt/bmc/skynet/lua /opt/bmc/apps/mdbctl/service/mdbctl.lua setprop set Bios_1_010101 bmc.kepler.Systems.Bios PcieCardBDF $input)
}

set_pcieaddrinfo() {
    source /etc/profile
    addrs=$(/opt/bmc/skynet/lua /opt/bmc/apps/mdbctl/service/mdbctl.lua lsobj PcieAddrInfo)
    addr_index=0
    echo "$addrs" | while IFS= read -r line; do
        remaining_part=${line#PcieAddrInfo_}
        addr_index=$((addr_index + 1))
        if [[ $remaining_part =~ [A-Za-z] ]]; then
            :
        else
            bdf=$(/data/script/load_pcie $addr_index)
            if [ -z "$bdf" ]; then
                continue
            fi
            bus=$(echo "$bdf" | awk '{print $1}')
            device=$(echo "$bdf" | awk '{print $2}')
            function=$(echo "$bdf" | awk '{print $3}')
            br=$(/opt/bmc/skynet/lua /opt/bmc/apps/mdbctl/service/mdbctl.lua setprop set $line bmc.kepler.Systems.PcieAddrInfo Bus $bus)
            dr=$(/opt/bmc/skynet/lua /opt/bmc/apps/mdbctl/service/mdbctl.lua setprop set $line bmc.kepler.Systems.PcieAddrInfo Device $device)
            fr=$(/opt/bmc/skynet/lua /opt/bmc/apps/mdbctl/service/mdbctl.lua setprop set $line bmc.kepler.Systems.PcieAddrInfo Function $function)
            sr=$(/opt/bmc/skynet/lua /opt/bmc/apps/mdbctl/service/mdbctl.lua setprop set $line bmc.kepler.Systems.PcieAddrInfo SlotID $addr_index)
        fi
    done
}

valid_UnitConfiguration() {
    source /etc/profile
    addrs=$(/opt/bmc/skynet/lua /opt/bmc/apps/mdbctl/service/mdbctl.lua lsobj UnitConfiguration)
    
    if [ "$addrs" = "Object not found." ]; then
        return 1
    else
        return 0
    fi
}

function_main() {
    source /etc/profile
    stored_md5=0
    
    # 等待直到配置存在
    while ! valid_UnitConfiguration; do
        sleep 10
    done
    
    while true; do
        current_md5=$(/usr/bin/md5sum /mockdata/IMU/pcie_card.json)
        if [ "$current_md5" != "$stored_md5" ]; then
            echo "pcie_card.json change..."
            set_pcieaddrinfo
            set_bios_pciecardbdf
            stored_md5=$current_md5
        else
            sleep 10
        fi
    done
}

function_main